<template>
    <div>
        <!-- 搜索 -->
        <el-form :inline="true">
            <el-form-item label="姓名">
                <el-input v-model="queryInfo.name" placeholder="请输入搜索姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryInfo.status" placeholder="全部" clearable>
                    <el-option label="启用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="queryInfo.deptId" placeholder="全部" clearable>
                    <el-option :label="item.name" :value="item.id" v-for="item in depts" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadUsers">查询</el-button>
                <el-button type="success" @click="addDialogVisible = true">添加</el-button>
                <el-button type="danger" @click="removeMultiple">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="userList" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column label="序号" type="index" width="80" />
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="电话" prop="phone" />
            <el-table-column label="地址" prop="address" />
            <el-table-column label="部门" prop="dept.name" />
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
                        @change="modifyStatus(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="removeById(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum" :page-sizes="[3, 10, 30, 50]" :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total" style="text-align: center;">
        </el-pagination>

        <!-- 添加对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed" :close-on-click-modal="false">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="addForm.address"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 修改对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible">
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="editForm.address"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
export default {
    data() {
        return {
            // 查询条件
            queryInfo: {
                pageNum: 1,
                pageSize: 3,
                name: '',
                phone: '',
                status: null,
                deptId: null
            },
            // 用户列表
            userList: [],
            // 总条数
            total: 0,
            // 添加对话框的显示与隐藏
            addDialogVisible: false,
            // 添加用户的表单校验规则
            addFormRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { pattern: /^1[3456789]\d{9}$/, message: '电话格式不正确', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' }
                ],
            },
            // 添加用户的表单数据
            addForm: {},
            // 修改用户的表单数据
            editForm: {},
            // 修改对话框的显示与隐藏
            editDialogVisible: false,
            //  多选框选中的数据
            multipleSelection: [],
            // 部门列表
            depts:[]
        }
    },
    created() {
        this.loadUsers()
        this.loadDepts()
    },
    methods: {
        async loadUsers() {
            const { data: res } = await this.$http.get('/user/queryByPage', {
                params: this.queryInfo
            })
            console.log(res)
            this.userList = res.data.list
            this.total = res.data.total
        },
        handleSizeChange(val) {
            this.queryInfo.pageSize = val
            this.loadUsers()
        },
        handleCurrentChange(val) {
            this.queryInfo.pageNum = val
            this.loadUsers()
        },
        // 删除用户
        removeById(id) {
            this.$confirm('确定要删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`/user/remove/${id}`)
                if (res.status != 200) {
                    return this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                this.loadUsers()
            }).catch(() => {
                this.$message.info('已取消删除')
            });
        },
        // 添加用户
        addUser() {
            // 1.校验表单数据
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) {
                    return
                }

                // 2.发送请求添加用户
                const { data: res } = await this.$http.post('/user/add', this.addForm)
                if (res.status != 200) {
                    return this.$message.error('添加失败')
                }
                // 提示添加成功
                this.$message.success('添加成功')
                // 关闭对话框
                this.addDialogVisible = false
                // 重新加载数据
                this.loadUsers()
            });
        },
        // 监听添加对话框的关闭
        addDialogClosed() {
            // 重置表单
            this.$refs.addFormRef.resetFields()
        },
        // 显示修改用户的对话框
        async showEditDialog(id) {
            const { data: res } = await this.$http.get(`/user/query/${id}`)
            if (res.status != 200) {
                return this.$message.error('获取用户信息失败')
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 修改用户
        editUser() {
            // 1.校验表单数据
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) {
                    return
                }

                // 2.发送请求修改用户
                const { data: res } = await this.$http.put('/user/modify', this.editForm)
                if (res.status != 200) {
                    return this.$message.error('修改失败')
                }
                // 提示修改成功
                this.$message.success('修改成功')
                // 关闭对话框
                this.editDialogVisible = false
                // 重新加载数据
                this.loadUsers()
            });
        },
        // 修改用户状态
        async modifyStatus(user) {
            const { data: res } = await this.$http.put(`/user/modifyStatus/${user.id}/${user.status}`)
            if (res.status !== 200) {
                return this.$message.error('修改状态失败')
            }
            this.$message.success('修改状态成功')
        },
        // 监听多选框的改变
        handleSelectionChange(val){
            this.multipleSelection = val;
        },
        // 批量删除
        removeMultiple(){
            // 1.判断是否有选中的数据
            if(this.multipleSelection.length === 0){
                return this.$message.error('请选择要删除的数据')
            }
            // 2.弹出提示框
            this.$confirm('确定要删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 3.发送请求删除数据
                const ids = this.multipleSelection.map(item => item.id)

                const { data: res } = await this.$http.delete('/user/removeBatch', {
                    data: ids
                })
                if (res.status !== 200) {
                    return this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                // 4.重新加载数据
                this.loadUsers()
            }).catch(() => {
                this.$message.info('已取消删除')
            });
        },
        // 加载部门列表
        async loadDepts(){
            const {data:res} = await this.$http.get('/dept/list')
            if(res.status !== 200){
                return this.$message.error('获取部门列表失败')
            }
            this.depts = res.data
            console.log(this.depts)
        }
    }
}
</script>

<style scoped></style>